package com.aijk.web.admin.controller.sys;

import com.aijk.base.entity.SysFlag;
import com.aijk.commons.exception.ErrorCodeException;
import com.aijk.commons.utils.Collections3;
import com.aijk.commons.utils.Utils;
import com.aijk.commons.web.constant.DubboVersionSystemConstant;
import com.aijk.pe.system.api.ModuleApi;
import com.aijk.pe.system.api.SysAdminApi;
import com.aijk.pe.system.api.SysRoleApi;
import com.aijk.pe.system.api.SysRoleAuthApi;
import com.aijk.pe.system.model.SysModule;
import com.aijk.pe.system.model.SysRole;
import com.aijk.pe.system.model.SysRoleAuth;
import com.aijk.pe.system.model.dto.SysRoleCreateDto;
import com.aijk.pe.system.model.qo.ModuleQo;
import com.aijk.pe.system.model.qo.RoleAuthQo;
import com.aijk.pe.system.model.qo.SysRoleQo;
import com.aijk.web.admin.RetMsg;
import com.aijk.web.admin.controller.BaseController;
import com.aijk.web.admin.entity.Constant;
import com.aijk.web.admin.entity.JsTree;
import com.aijk.web.admin.service.ModuleService;
import com.aijk.web.admin.utils.CompanyUtil;
import com.aijk.web.admin.utils.DataTableUtil;
import com.aijk.web.admin.utils.ModuleTreeUtils;
import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Controller
@RequestMapping(value = "/admin/sys/role")
public class SysRoleController extends BaseController {

    protected Logger logger = LoggerFactory.getLogger(this.getClass());

    @Reference(version = DubboVersionSystemConstant.DUBBO_VERSION_SYS_ROLE_API)
    private SysRoleApi roleApi;

    @Reference(version = DubboVersionSystemConstant.DUBBO_VERSION_SYS_ROLE_AUTH_API)
    private SysRoleAuthApi authApi;

    @Reference(version = DubboVersionSystemConstant.DUBBO_VERSION_SYS_ADMIN_API)
    private SysAdminApi adminApi;

    @Reference(version = DubboVersionSystemConstant.DUBBO_VERSION_SYS_MODULE_API)
    private ModuleApi moduleApi;

    @Autowired
    private ModuleService moduleService;

    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @RequiresPermissions("admin:sys:role:list")
    public String list_view() {
        return "sys/role_list";
    }

    @RequestMapping(value = "/list", method = RequestMethod.POST)
    @ResponseBody
    @RequiresPermissions("admin:sys:role:list")
    public RetMsg list(@RequestParam HashMap skey, @RequestParam(value = "draw", defaultValue = "1") Integer draw) {
        Long iTotalRecords;
        DataTableUtil.FormatOptions(skey);
        CompanyUtil.addAuth(skey, getCurrentUser());
        SysRoleQo qo = DataTableUtil.fillQo(skey, SysRoleQo.class);
        draw += 1;
        PageInfo<SysRole> list = roleApi.getPage(qo);

        iTotalRecords = list.getTotal();
        RetMsg regMsg = new RetMsg();

        regMsg.put("data", list.getList());
        regMsg.put("draw", draw);
        regMsg.put("recordsTotal", iTotalRecords);
        regMsg.put("recordsFiltered", iTotalRecords);

        return regMsg;
    }

    @RequestMapping(value = "/add", method = RequestMethod.GET)
    public String add_view(Model model) {
        model.addAttribute("method", "add");
        return "sys/role_edit";
    }

    @RequestMapping(value = "/add", method = RequestMethod.POST)
    @ResponseBody
    public RetMsg add(@Valid SysRoleCreateDto role) {
        try {
            if (isSubCompany()){
                role.setCompanyId(getCurrentUser().getCompanyId());
            }
            role.setSysFlag(Constant.SYS_PE_FLAG);
            roleApi.save(role);
        } catch (ErrorCodeException e) {
            e.printStackTrace();
            return RetMsg.failed();
        }
        return RetMsg.success();
    }

    @RequestMapping(value = "/update", method = RequestMethod.GET)
    public String update_view(@RequestParam(value = "id") Integer id, Model model) {
        SysRole role = roleApi.get(id);
        RoleAuthQo qo = new RoleAuthQo();
        qo.setRid(id);
        List<SysRoleAuth> auths = authApi.getList(qo);
        String permIds = "";
        for (SysRoleAuth auth : auths) {
            permIds = permIds + auth.getMid() + ",";
        }
        if (permIds.length() > 0)
            model.addAttribute("permIds", permIds.substring(0, permIds.length() - 1));
        model.addAttribute("role", role);
        model.addAttribute("method", "update");
        return "sys/role_edit";
    }

    @RequestMapping(value = "/update", method = RequestMethod.POST)
    @ResponseBody
    public RetMsg update(@Valid SysRoleCreateDto role) {
        try {
            role.setSysFlag(getCurrentUser().getSysFlag());
            roleApi.save(role);
        } catch (ErrorCodeException e) {
            e.printStackTrace();
            return RetMsg.failed();
        }
        return RetMsg.success();
    }

    @RequestMapping(value = "/del", method = RequestMethod.POST)
    @ResponseBody
    public RetMsg del(@RequestParam(value = "id") Integer id) {
        try {
            roleApi.delete(id);
        } catch (ErrorCodeException e) {
            e.printStackTrace();
            return RetMsg.failed();
        }
        return RetMsg.success();
    }

    @RequestMapping(value = "/tree", method = RequestMethod.GET)
    public
    @ResponseBody
    String tree(@RequestParam(value = "rid", required = false) Integer rid) {
        List<Integer> authList = new ArrayList<>();
        if (Utils.isNotEmpty(rid)) {
            RoleAuthQo qo = new RoleAuthQo();
            qo.setRid(rid);
            List<SysRoleAuth> auths = authApi.getList(qo);
            authList = Collections3.extractToList(auths, "mid");
        }

        ModuleQo qo = new ModuleQo();
        qo.setSysFlag(getCurrentUser().getSysFlag());
        qo.setSortway("OrderNo");
        List<SysModule> list = moduleApi.get(qo);

        List<JsTree> treedata = ModuleTreeUtils.getModuleTree(list, authList);

        return JSON.toJSONString(treedata);
    }

    @RequestMapping(value = "/existed", method = RequestMethod.POST)
    @ResponseBody
    public RetMsg existed(@Valid SysRole role) {
        try {
            SysRoleQo qo = new SysRoleQo();
            if(Utils.isNotEmpty(role.getRoleId())){
                qo.setRoleIdNotEqual(role.getRoleId());
            }
            if(Utils.isNotEmpty(role.getRoleName())){
                qo.setRoleName(role.getRoleName());
                if(isSubCompany()){
                    qo.setCompanyId(getCurrentUser().getCompanyId());
                }else{
                    qo.setCompanyIsNull(true);
                }
                List<SysRole> roles = roleApi.getList(qo);
                if(roles.size()>0) return RetMsg.failed();
            }

        }catch (ErrorCodeException e){
            e.printStackTrace();
            return RetMsg.failed();
        }
        return RetMsg.success();
    }

}
